import Vue from 'vue'
import VueRouter from 'vue-router'

const Home = () => import(/* webpackChunkName: 'Home' */'../pages/Home.vue')
const Login = () => import(/* webpackChunkName: 'Home' */'../pages/Login.vue')

const Users = () => import(/* webpackChunkName: 'Users' */'../pages/user/Users.vue')

const Roles = () => import(/* webpackChunkName: 'Rights' */'../pages/rights/Roles.vue')
const Rights = () => import(/* webpackChunkName: 'Rights' */'../pages/rights/Rights.vue')

const Goods = () => import(/* webpackChunkName: 'Goods' */'../pages/products/Goods.vue')
const Categories = () => import(/* webpackChunkName: 'Goods' */'../pages/products/Categories.vue')
const GoodsAdd = () => import(/* webpackChunkName: 'Goods' */'../pages/products/GoodsAdd.vue')

Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'history',
  routes: [
    {
      path: '/',
      redirect: '/home'
    },
    {
      path: '/login',
      component: Login
    },
    {
      path: '/home',
      component: Home,
      children: [
        {
          path: '/users',
          component: Users
        },
        {
          path: '/roles',
          component: Roles
        },
        {
          path: '/rights',
          component: Rights
        },
        {
          path: '/goods',
          component: Goods
        },
        {
          path: '/categories',
          component: Categories
        },
        {
          path: '/goods-add',
          component: GoodsAdd
        }
      ]
    }
  ]
})

// 注册了前置的导航守卫
router.beforeEach(function (to, from, next) {
  const token = localStorage.getItem('token')
  if (to.path === '/login' || token) {
    next()
  } else {
    next('/login')
  }
})

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

export default router
